"""
Author: HuWen
@file: page_warehouse.py
@dateTime: 2025/9/4 09:08
加油加油！！！
"""
from common.base_page import BasePage
from common.locate_by import By
from playwright.sync_api import Page, FrameLocator
import inspect
from locators.basicSecurityInformation.basicProcessInfo.loc_warehouse_management import WareHouse


class WareHousePage(BasePage):
    # 定义富文本类型标识（在当前类内部使用）
    RICH_TEXT_TYPE = 'rich_text'
    # 富文本iframe的title
    RICH_TEXT_IFRAME_TITLE = "Rich Text Area"
    # 富文本编辑区的label
    RICH_TEXT_EDITOR_LABEL = "编辑区. 按Alt+0键打开帮助"

    def __init__(self, page: Page):
        super().__init__(page)
        self.switch_menu("安全基础管理")
        self.switch_menu("生产档案(企业)")
        self.check(WareHouse.loc_lab_warehouse)

        # 自动生成配置列表
        self.filed_configs = self._generate_filed_configs()

    def _generate_filed_configs(self):
        """自动从WareHouse类中提取元素并生成配置列表，包括富文本类型"""
        configs = []

        # 获取WareHouse类的所有属性
        loc_attributes = inspect.getmembers(WareHouse)

        # 筛选出以'loc_add_'开头的属性
        for name, value in loc_attributes:
            if name.startswith('loc_add_') and isinstance(value, dict) and 'loc_role' in value:
                # 确定操作类型，使用字符串标识富文本类型
                if value['loc_role'] in (By.textbox, 'textbox'):
                    action = 'fill'
                elif value['loc_role'] in (By.combobox, 'combobox'):
                    action = 'select'
                # 识别富文本类型（使用字符串判断，不依赖By类）
                elif value['loc_role'] == self.RICH_TEXT_TYPE:
                    action = 'fill_rich_text'
                else:
                    continue

                # 生成数据键名
                data_key = name[len('loc_add_'):]
                configs.append((action, value, data_key))

        return configs

    # def _get_rich_text_frame(self) -> FrameLocator:
    #     """获取富文本编辑器的iframe定位器，通过title直接定位"""
    #     return self.page.frame_locator(f"iframe[title=\"{self.RICH_TEXT_IFRAME_TITLE}\"]")

    def fill_rich_text(self, content: str):
        """在富文本编辑器中输入内容，按录制脚本逻辑，合并iframe定位与编辑区操作"""
        # 直接定位富文本的iframe
        frame = self.page.frame_locator(f"iframe[title=\"{self.RICH_TEXT_IFRAME_TITLE}\"]")
        # 定位富文本编辑区
        editor = frame.get_by_label(self.RICH_TEXT_EDITOR_LABEL)
        editor.click()  # 点击编辑区，确保激活
        editor.fill("")  # 清空现有内容
        editor.type(content, delay=50)  # 模拟真实输入

    def create_warehouse(self, data: dict):
        """执行创建操作，包括富文本处理"""
        self.click(WareHouse.loc_add_warehousebutton)

        # 遍历配置列表执行对应操作
        for action, locator, data_key in self.filed_configs:
            value = data.get(data_key, "")
            if action == 'fill':
                self.fill(locator, value)
            elif action == 'select':
                self.select(locator, value)
            elif action == 'fill_rich_text' and value:
                # 处理富文本输入，直接调用方法传入内容
                self.fill_rich_text(value)

        # 点击确定按钮
        self.click(WareHouse.loc_add_ok)